package com.example.auction.activity;

import android.content.SharedPreferences;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import com.example.auction.R;
import com.example.auction.sqlite.Sqlite;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

public class LoginActivity extends Activity {
    private Button btn_login;
    private EditText et_input_username, et_input_password;
    private ImageView mClearUserNameView, mClearPasswordView;
    private TextView tv_reg;
    private RadioGroup rg_power;
    private CheckBox mEyeView;

    //admin为0是用户权限，为1是管理员权限
    private Integer admin = 0;
    private String username = "";
    private String userpass = "";

    Sqlite sqlite = new Sqlite(LoginActivity.this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //获取控件对象
        findViewId();
        //初始化
        init();

        //点击眼睛隐藏密码
        mEyeView.setOnCheckedChangeListener(new eyeClick());
        btn_login.setOnClickListener(new loginButton());
        tv_reg.setOnClickListener(new regTextView());

    }

    private void init() {

        //自动登录
        SharedPreferences spf = getSharedPreferences("loginData", MODE_PRIVATE);
        boolean isAutoLogin = spf.getBoolean("isAutoLogin", false);
        String localName = spf.getString("localName", "");
        int adminNum = spf.getInt("adminNum", 0);

        if (isAutoLogin) {
            //登录成功
            Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
            //跳转到主页面
            Intent intent = new Intent();
            intent.putExtra("user_id", getId(localName, adminNum));
            if (adminNum == 0) {
                intent.setClass(LoginActivity.this, UserUIBaseActivity.class);
            } else if (adminNum == 1) {
                intent.setClass(LoginActivity.this, AdminUIBaseActivity.class);
            }
            startActivity(intent);
            LoginActivity.this.finish();
        }

        //清空输入按钮
        mClearUserNameView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_input_username.setText("");
            }
        });
        mClearPasswordView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_input_password.setText("");
            }
        });

        //单选框选择监听
        rg_power.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_user:
                        admin = 0;
                        break;
                    case R.id.rb_admin:
                        admin = 1;
//                        rb_admin.setTextColor(0xff0000ff);
//                        rb_user.setTextColor(0xff000000);
                        break;
                    default:
                        break;
                }
            }
        });

    }

    //登录按钮
    private class loginButton implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            //获取输入数据
            username = et_input_username.getText().toString().trim();
            userpass = et_input_password.getText().toString().trim();
            //判断是否为空
            if (username.equals("") || userpass.equals("")) {
                Toast.makeText(getApplicationContext(), "请输入用户名或密码", Toast.LENGTH_SHORT).show();
            } else {
                //判断输入的用户名或管理员是否存在
                if (getusername(username, admin) != null) {
                    //获取密码进行比对
                    if (getpwd(username, admin).equals(userpass)) {
                        //登录成功
                        Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();

                        //本地存储是否自动登录的值
                        SharedPreferences spf = getSharedPreferences("loginData", MODE_PRIVATE);
                        SharedPreferences.Editor edit = spf.edit();
                        //isAutoLogin设为true则下次打开app会自动登录
                        edit.putBoolean("isAutoLogin", true);
                        edit.putString("localName", username);
                        edit.putString("localPass", userpass);
                        //跳转到主页面,并存储admin的值
                        Intent intent = new Intent();
                        intent.putExtra("user_id", getId(username, admin));
                        if (admin == 0) {
                            intent.setClass(LoginActivity.this, UserUIBaseActivity.class);
                            edit.putInt("adminNum", 0);
                        } else if (admin == 1) {
                            intent.setClass(LoginActivity.this, AdminUIBaseActivity.class);
                            edit.putInt("adminNum", 1);
                        }
                        edit.apply();

                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        LoginActivity.this.finish();
                    } else {
                        Toast.makeText(getApplicationContext(), "用户名或密码错误", Toast.LENGTH_SHORT).show();
                        //清空密码
                        et_input_password.setText("");
                    }
                }
               /* 永远执行不到
               else {
                    //用户名或管理员不存在
                    if (admin == 0) {
                        regTips();
                    } else if (admin == 1) {
                        Toast.makeText(getApplicationContext(), "这不是管理员", Toast.LENGTH_SHORT).show();
                    }

                }*/
            }
        }
    }


    //点击眼睛图标显示或隐藏密码
    private class eyeClick implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                et_input_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                et_input_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
        }
    }

    private void findViewId() {
        btn_login = (Button) findViewById(R.id.btn_login);
        tv_reg = findViewById(R.id.tv_reg);

        rg_power = (RadioGroup) findViewById(R.id.rg_power);
        et_input_username = (EditText) findViewById(R.id.et_input_username);
        et_input_password = (EditText) findViewById(R.id.et_input_password);

        mClearUserNameView = findViewById(R.id.iv_clear_username);
        mClearPasswordView = findViewById(R.id.iv_clear_password);
        mEyeView = findViewById(R.id.cb_login_open_eye);
    }

    //根据用户名获取用户行
    private Cursor getusername(String username, Integer admin1) {
        Cursor cursor = null;
        cursor = sqlite.selectUser(username, admin1);
        return cursor;
    }

    //获取密码
    @SuppressLint("Range")
    private String getpwd(String username, Integer admin1) {
        String userpass = "";
        Cursor cursor = null;
        cursor = sqlite.selectUser(username, admin1);

        if (cursor != null && cursor.moveToFirst()) {
            userpass = cursor.getString(cursor.getColumnIndex("user_pass"));
        }
        return userpass;
    }

    //取得登陆用户的id
    @SuppressLint("Range")
    private Integer getId(String username, Integer admin1) {
        int user_id = 0;
        Cursor cursor = sqlite.selectUser(username, admin1);

        if (cursor != null && cursor.moveToFirst()) {
            user_id = cursor.getInt(cursor.getColumnIndex("user_id"));
        }
        return user_id;
    }

    //注册文本按钮
    private class regTextView implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        }
    }

    //提示注册
    private void regTips() {
        //设置一个信息提示框，用户是否注册
        Toast.makeText(getApplicationContext(), "用户未注册，请注册", Toast.LENGTH_SHORT).show();
        AlertDialog.Builder dialog = new AlertDialog.Builder(LoginActivity.this);
        dialog.setTitle("用户名不存在");
        dialog.setMessage("是否注册？");

        dialog.setPositiveButton("是", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //跳转到注册页面
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, RegisterActivity.class);

                startActivity(intent);
                //LoginActivity.this.finish();
            }
        });
        dialog.setNegativeButton("否", null);
        dialog.show();
    }

}
